<template>
	<page-wrapper :show-tab-bar="false"  :navTitle="isEdit ? '修改预算' : '创建预算'" navBackgroundColor="#FFD84D">
		<view class="budget-edit-container">
			<!-- 自定义导航栏 -->
			<!-- <CustomNavbar :title="isEdit ? '修改预算' : '创建预算'" backgroundColor="#FFD84D"></CustomNavbar> -->
			
			<!-- 表单内容 -->
			<view class="form-content">
				<view class="form-item">
					<text class="form-label">{{ currentYear }}年{{ currentMonth }}月预算金额</text>
					<view class="input-wrapper">
						<text class="currency-symbol">¥</text>
						<input
							class="budget-input"
							type="digit"
							v-model="budgetAmount"
							placeholder="请输入预算金额"
							focus
						/>
					</view>
				</view>
				
				<!-- 操作按钮 -->
				<view class="form-actions">
					<button class="cancel-btn" @click="goBack">取消</button>
					<button class="save-btn" @click="saveBudget" :disabled="!isValidAmount">保存</button>
				</view>
			</view>
		</view>
	</page-wrapper>
</template>

<script>
import { addBudget, updateBudget } from '@/api/budget.js';
import { themeMixin } from '@/utils/theme.js';

export default {
	mixins: [themeMixin],
	data() {
		return {
			isEdit: false,       // 是否为编辑模式
			budgetId: null,      // 预算ID
			budgetAmount: '',    // 预算金额
			currentYear: new Date().getFullYear(),  // 当前年份
			currentMonth: new Date().getMonth() + 1 // 当前月份
		};
	},
	computed: {
		// 判断金额是否有效
		isValidAmount() {
			return this.budgetAmount !== '' && !isNaN(parseFloat(this.budgetAmount)) && parseFloat(this.budgetAmount) > 0;
		}
	},
	onLoad(options) {
		// 解析传递的参数
		if (options.budgetData) {
			const budgetData = JSON.parse(decodeURIComponent(options.budgetData));
			this.isEdit = true;
			this.budgetId = budgetData.id;
			this.budgetAmount = budgetData.totalBudget.toString();
			this.currentYear = budgetData.year || this.currentYear;
			this.currentMonth = budgetData.month || this.currentMonth;
		} else if (options.params) {
			const params = JSON.parse(decodeURIComponent(options.params));
			this.currentYear = params.year || this.currentYear;
			this.currentMonth = params.month || this.currentMonth;
		}
	},
	methods: {
		// 返回上一页
		goBack() {
			uni.navigateBack();
		},
		
		// 保存预算
		saveBudget() {
			if (!this.isValidAmount) {
				uni.showToast({
					title: '请输入有效的预算金额',
					icon: 'none'
				});
				return;
			}
			
			// 显示加载中
			uni.showLoading({
				title: '保存中...'
			});
			
			// 构建预算对象
			const budget = {
				amount: parseFloat(this.budgetAmount),
				createTime: `${this.currentYear}-${String(this.currentMonth).padStart(2, '0')}-14 11:10:00` // 使用选中的年月
			};
			
			// 如果是编辑模式，添加ID
			if (this.isEdit && this.budgetId) {
				budget.id = this.budgetId;
				
				// 调用更新预算API
				updateBudget(budget)
					.then(res => {
						uni.hideLoading();
						console.log('更新预算成功:', res.data);
						
						if (res.data.code === 200) {
							uni.showToast({
								title: '预算更新成功',
								icon: 'success'
							});
							setTimeout(() => {
								uni.navigateBack();
							}, 1500);
						} else {
							uni.showToast({
								title: res.data.msg || '预算更新失败',
								icon: 'none'
							});
						}
					})
					.catch(err => {
						uni.hideLoading();
						console.error('更新预算失败:', err);
						uni.showToast({
							title: '预算更新失败',
							icon: 'none'
						});
					});
			} else {
				// 调用添加预算API
				addBudget(budget)
					.then(res => {
						uni.hideLoading();
						console.log('添加预算成功:', res.data);
						
						if (res.data.code === 200) {
							uni.showToast({
								title: '预算创建成功',
								icon: 'success'
							});
							setTimeout(() => {
								uni.navigateBack();
							}, 1500);
						} else {
							uni.showToast({
								title: res.data.msg || '预算创建失败',
								icon: 'none'
							});
						}
					})
					.catch(err => {
						uni.hideLoading();
						console.error('添加预算失败:', err);
						uni.showToast({
							title: '预算创建失败',
							icon: 'none'
						});
					});
			}
		},
		
		// 格式化日期时间为 yyyy-MM-dd HH:mm:ss
		formatDateTime(date) {
			const year = date.getFullYear();
			const month = String(date.getMonth() + 1).padStart(2, '0');
			const day = String(date.getDate()).padStart(2, '0');
			const hours = String(date.getHours()).padStart(2, '0');
			const minutes = String(date.getMinutes()).padStart(2, '0');
			const seconds = String(date.getSeconds()).padStart(2, '0');
			
			return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
		}
	}
}
</script>

<style lang="scss">
.budget-edit-container {
	background-color: $background-color;
	height: 100%;
	
	.form-content {
		background-color: #fff;
		padding: 40rpx;
		// margin-top: 20rpx;
		
		.form-item {
			margin-bottom: 40rpx;
			
			.form-label {
				font-size: 28rpx;
				color: $text-color-lighter;
				margin-bottom: 20rpx;
				display: block;
			}
			
			.input-wrapper {
				display: flex;
				align-items: center;
				border-bottom: 1px solid $border-color;
				padding-bottom: 20rpx;
				
				.currency-symbol {
					font-size: 40rpx;
					color: $text-color;
					margin-right: 10rpx;
				}
				
				.budget-input {
					flex: 1;
					font-size: 40rpx;
					height: 80rpx;
					color: $text-color;
				}
			}
		}
		
		.form-actions {
			display: flex;
			justify-content: space-between;
			margin-top: 80rpx;
			
			button {
				flex: 1;
				height: 80rpx;
				line-height: 80rpx;
				font-size: 32rpx;
				border-radius: 40rpx;
				
				&.cancel-btn {
					background-color: #f5f5f5;
					color: $text-color;
					margin-right: 20rpx;
				}
				
				&.save-btn {
					background-color: $primary-color;
					color: $text-color-white;
					margin-left: 20rpx;
					
					&:disabled {
						opacity: 0.5;
					}
				}
			}
		}
	}
}
</style> 